package com.zzy.adpter;

import com.alibaba.fastjson.JSONObject;
import com.zzy.pojo.UserInfo;
import com.zzy.service.UserService;
import com.zzy.util.HttpClientUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

import java.util.Date;

import static javax.swing.UIManager.getString;

@Component
public class Login3rdAdapter extends UserService implements Login3rdTarget{

    @Value(value = "${gitee.state}")
    private String giteeState;

    @Value(value = "${gitee.token.url}")
    private String giteeTokenUrl;

    @Value(value = "${gitee.user.url}")
    private String giteeUserUrl;

    @Value(value = "${gitee.user.prefix}")
    private String giteeUserPrefix;

    @Override
    public String loginByGitee(String code, String state) {
        if(!giteeState.equals(state)) {
            throw new UnsupportedOperationException("Invalid State!");
        }
        String tokenUrl = giteeTokenUrl.concat(code);
        JSONObject tokenResponse = HttpClientUtils.execute(tokenUrl, HttpMethod.POST);
        String token = tokenResponse.getString("access_token");
        String userUrl = giteeUserUrl.concat(token);
        String name = HttpClientUtils.execute(userUrl, HttpMethod.GET).getString("name");
        String userName = giteeUserPrefix.concat(name);
        String password = userName;
        return autoRegister3rdAndLogin(userName, password);
    }

    private String autoRegister3rdAndLogin(String userName, String password) {
        // 如果三方已经登陆过，直接登录
        if(super.checkUserExist(userName)){
            return super.login(userName, password);
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setCreateDate(new Date());
        userInfo.setUserName(userName);
        userInfo.setUserPassword(password);
        super.register(userInfo);
        return super.login(userName, password);
    }

    @Override
    public String loginByWechat(String... params) {
        return null;
    }

    @Override
    public String loginByQQ(String... params) {
        return null;
    }
}
